<?php
namespace Index\Controller;
use Think\Controller;

class LoginController extends Controller{
   public function indexAction(){

      if (IS_POST) {
         $username = I('post.user_name');
         $password = md5(I('post.password'));
         $model = M();
         $isName= $model->query("select gid,username,id,face_url from user where username ='{$username}'  and password ='{$password}'");
         $isMail = $model->query("select gid,username,id,face_url from user where mail ='{$username}'  and password ='{$password}'");
         if($isName[0]['gid']==3 || $isMail[0]['gid']==3){
            $this->error('你已被管理设置权限，无法登录', '', 2);
         }
         if (empty($isName) && empty($isMail)) {
            $this->error('用户名或密码错误', '', 2);
         }else{
            $userInfo = empty($isName) ? $isMail[0] : $isName[0];
            $_SESSION['username'] =  $userInfo['username'];
            $_SESSION['uid'] = $userInfo['id'];
            $_SESSION['gid'] = $userInfo['gid'];
            $_SESSION['face_url'] = $userInfo['face_url'];
            $login_time = time();
            $model->execute("update user set login_time = '{$login_time}' where id ='{$_SESSION['uid']}'");
//            session_start();
//            setcookie(session_name(),session_id(),time()+60);

            $this->success('登录成功', U("Index/index"), 2);

         }
      } else {
         $this->display('index');
      }

   }

   public function logoutAction(){

      $model = M();
      $login_time = $model->query("select login_time from user where id ='{$_SESSION['uid']}'");

      $logout_time = time();
      $online_time = $logout_time - $login_time[0]['login_time'];
      $oldtime = $model->query("select online_time from user where id ='{$_SESSION['uid']}'");

      $online_time = $online_time + $oldtime[0]['online_time'];
      $model->execute("update user set logout_time = '{$logout_time}', online_time = '{$online_time}' where id ='{$_SESSION['uid']}'");

      session_unset();
      session_destroy();
      $this->success('退出成功',U("Index/index"),2);
   }
}
